import {designComponent, iHTMLDivElement, onMounted, PropType, reactive, useRefs} from "@peryl/react-compose";
import {eRenderMode, execIndexScript, execMainScript, getGlobalCacheScript, iIndexData, iMicroApp, iMicroMainConfig, iMicroMainRenderModeBase, iMicroTokenInfo} from '@peryl/micro-web';
import {$notice, ApplicationConfigurationProvider} from "plain-design";
import {microLoadingHook} from "./useMicroLoading";

export const FrameModeNone = designComponent({
  props: {
    indexData: { type: Object as PropType<iIndexData>, required: true },
    microApp: { type: Object as PropType<iMicroApp>, required: true },
    tokenInfo: { type: Object as PropType<iMicroTokenInfo>, required: true },
  },
  setup({ props }) {

    const configuration = ApplicationConfigurationProvider.inject();

    const { microApp } = props;

    const { refs, onRef } = useRefs({ el: iHTMLDivElement });

    const state = reactive({
      getPageComponent: null as null | iMicroMainRenderModeBase['getPageComponent']
    });

    const onComplete = (error?: string | null | undefined) => {microLoadingHook.exec({ id: props.indexData.microConfig.id, error });};

    onMounted(async () => {

      try {
        const Win = window;
        const globalCacheScript = getGlobalCacheScript(Win);

        const indexConfig = await execIndexScript({ indexData: props.indexData, Win, globalCacheScript, microApp });
        const indexConfigMainValue = await indexConfig.main();
        const mainConfig: iMicroMainConfig = await execMainScript({ indexConfigMainValue, indexData: props.indexData, Win, globalCacheScript, onFailed: ({ error, url }) => $notice.error(`加载子应用[${props.indexData.microConfig.id}]main config失败！` + url + `，错误信息：` + JSON.stringify(error)) });
        const subRoutePublicPath = microApp.route.buildMicroPublicPath({ microConfig: props.indexData.microConfig, subMicroPublicPath: mainConfig.getPublicPath() });

        microApp.defer.loadMicroInfoMap[props.indexData.microConfig.id].resolve({ subRoutePublicPath, Win, mainConfig });
        await microApp.defer.loadMicroReadyMap[props.indexData.microConfig.id].promise;

        const { renderMode } = props.indexData;
        if (renderMode === eRenderMode.base) {
          if ('base' in mainConfig.frameMode) {
            state.getPageComponent = mainConfig.frameMode.base.getPageComponent;
          } else {
            const errMsg = `子应用[${props.indexData.microConfig.id}]执行 mainConfig失败，当data-micro-render为base时，子应用的mainConfig必须配置frameMode.base`;
            console.error(errMsg);
            // $notice.error(errMsg);
            throw new Error(errMsg);
          }
        } else {
          if ('custom' in mainConfig.frameMode) {
            const appContainer = Win.document.createElement('div');
            appContainer.setAttribute('data-micro-root', props.indexData.microConfig.id);
            refs.el!.appendChild(appContainer);
            mainConfig.frameMode.custom.init({ microConfig: props.indexData.microConfig, microApp, subRoutePublicPath, el: appContainer, dark: configuration.value.theme.dark, primary: configuration.value.theme.base.primary });
          } else {
            const errMsg = `子应用[${props.indexData.microConfig.id}]执行 mainConfig失败，当data-micro-render为custom时，子应用的mainConfig必须配置frameMode.custom`;
            console.error(errMsg);
            // $notice.error(errMsg);
            throw new Error(errMsg);
          }
        }
        onComplete();
      } catch (e: any) {
        const errMsg = `加载子应用[${props.indexData.microConfig.id}]失败，错误信息：` + (e.message || JSON.stringify(e));
        console.log(errMsg);
        $notice.error(errMsg);
        onComplete(errMsg);
        throw e;
      }
    });

    return () => (
      <div data-micro-container={props.indexData.microConfig.id} data-micro-frame-mode-none={props.indexData.microConfig.id} ref={onRef.el}>
        {props.indexData.renderMode === eRenderMode.base && !!state.getPageComponent && (
          <microApp.PageList microConfig={props.indexData.microConfig} getPageComponent={state.getPageComponent}/>
        )}
      </div>
    );
  },
});
